package dataStructure.xmg1.a06;

import dataStructure.xmg1.a06.printer.BinaryTreeInfo;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: vince_zww
 * @date: 2020/12/11 0:35
 * @desceription: 二叉搜索树
 */
public class BinarySearchTree<E> implements BinaryTreeInfo {
    public int size;
    private Node<E> root;
    private Comparator<E> comparator;

    public BinarySearchTree() {
        this(null);
    }

    public BinarySearchTree(Comparator<E> comparator) {
        this.comparator = comparator;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void clear() {
        root = null;
        size = 0;
    }

    public void add(E element) {
        elementNotNullCheck(element);
        // 添加第一个节点
        if (root == null) {
            root = new Node<>(element, null);
            size++;
            return;
        }
        // 添加的不是第一个节点
        // 找到父节点
        Node<E> parent = null;
        Node<E> node = root;
        int cmp = 0;
        while (node != null) {
            cmp = compare(element, node.element);
            parent = node;
            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {// 相等
                node.element = element;
                return;
            }
        }
        // 看看插入到父节点的哪个位置
        Node<E> newNode = new Node<>(element, parent);
        if (cmp > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        size++;
    }

    //先找到节点，然后再把节点删掉
    //度为0：直接删除，度为1：用子节点代替父节点，度为2：用前驱或后继节点替代
    public void remove(E element) {
        remove(node(element));
    }

    public boolean contains(E element) {
        return node(element) != null;
    }

    private void remove(Node<E> node) {
        if (node == null)return;
        size--;

        if (node.hasTwoChildern()) {//度为2个节点
            //找到前驱节点
            Node<E> p = successor(node);
            //用前驱节点的值覆盖度为2的节点的值
            node.element = p.element;
            //删除前驱节点
            node = p;
        }
        //删除node节点(node的度必然是1或者0)
        Node<E> replacement = node.left != null ? node.left : node.right;
        if (replacement != null) {// node是度为1的节点
            //更改parent
            replacement.parent = node.parent;
            //更改parent left、right的指向
            if (node.parent == null) {//node是度为1的节点并且是根节点
                root = replacement;
            }
            else if (node == node.parent.left) {
                node.parent.left = replacement;

            } else {// (node == node.parent.right)
                node.parent.right = replacement;
            }
        } else if (node.parent == null) {//node是叶子节点并且是根节点
            root = null;
        } else {//node是叶子节点，但不是根节点
            if (node == node.parent.left) {
                node.parent.left = null;
            } else { //node == node.parent.right
                node.parent.right = null;
            }
        }
    }

    private Node<E> node(E element) {
        Node<E> node = root;
        while (node != null) {
            int cmp = compare(element, node.element);
            if (cmp == 0) return node;
            if (cmp > 0) {
                node = node.right;
            } else {//cmp<0
                node = node.left;
            }
        }
        return null;
    }

//    //前序遍历
//    public void preorderTraversal(){
//        preorderTraversal(root);
//
//    }
//    //前序遍历
//    public void preorderTraversal(Node<E> node){
//        if (node == null) return;
//        System.out.println(node.element);
//        preorderTraversal(node.left);
//        preorderTraversal(node.right);
//    }
//
//    //中序遍历
//    public void inorderTraversal(){
//        inorderTraversal(root);
//    }
//    //中序遍历
//    private void inorderTraversal(Node<E> node){
//        if (node == null) return;
//        inorderTraversal(node.left);
//        System.out.println(node.element);
//        inorderTraversal(node.right);
//    }
//
//    //后序遍历
//    public void postorderTraversal(){
//        postorderTraversal(root);
//    }
//    //后序遍历
//    public void postorderTraversal(Node<E> node){
//        if (node == null) return;
//        postorderTraversal(node.left);
//        postorderTraversal(node.right);
//        System.out.println(node.element);
//    }
//
//    //层序遍历
//    public void levelOrderTraversal() {
//        if (root == null) return;
//        Queue<Node<E>> queue = new LinkedList<>();
//        //入队
//        queue.offer(root);
//        while (!queue.isEmpty()) {
//            //出队
//            Node<E> node = queue.poll();
//            System.out.println(node.element);
//            if (node.left != null) {
//                //入队
//                queue.offer(node.left);
//            }
//            if (node.right != null) {
//                //入队
//                queue.offer(node.right);
//            }
//        }
//    }

    //前序遍历
    public void preorder(Visitor<E> visitor) {
        if (visitor == null) return;
        preorder(root, visitor);
    }

    private void preorder(Node<E> node, Visitor<E> visitor) {
        if (node == null|| visitor.stop) return;

        visitor.stop = visitor.visit(node.element);
        preorder(node.left, visitor);
        preorder(node.right, visitor);
    }

    //中序遍历
    public void inorder(Visitor<E> visitor) {
        if (visitor == null) return;
        inorder(root, visitor);
    }

    private void inorder(Node<E> node, Visitor<E> visitor) {
        if (node == null|| visitor.stop) return;
        inorder(node.left, visitor);
        if (visitor.stop) return;;
        visitor.stop = visitor.visit(node.element);
        inorder(node.right, visitor);
    }


    //后序遍历
    public void postorder(Visitor<E> visitor) {
        if (visitor == null) return;
        postorder(root, visitor);
    }

    private void postorder(Node<E> node, Visitor<E> visitor) {
        if (node == null|| visitor.stop) return;

        postorder(node.left, visitor);
        postorder(node.right, visitor);
        if (visitor.stop) return;;
        visitor.stop = visitor.visit(node.element);
    }


    //层序遍历
    public void levelOrder(Visitor<E> visitor) {
        if (root == null || visitor == null) return;
        Queue<Node<E>> queue = new LinkedList<>();
        //入队
        queue.offer(root);
        while (!queue.isEmpty()) {
            //出队
            Node<E> node = queue.poll();
            if (visitor.visit(node.element)) {
                return;
            }
            if (node.left != null) {
                //入队
                queue.offer(node.left);
            }
            if (node.right != null) {
                //入队
                queue.offer(node.right);
            }
        }
    }

    //判断是否完全二叉树——第一种写法
//    public boolean isCompare(){
//        if (root == null)return false;
//
//        Queue<Node<E>> queue = new LinkedList<>();
//        queue.offer(root);
//
//        boolean leaf = false;
//        while (!queue.isEmpty()) {
//            Node<E> node = queue.poll();
//
//            if (leaf && !node.isLeaf()) return false;
//
//            if (node.left != null && node.right != null) {
//                queue.offer(node.left);
//                queue.offer(node.right);
//            } else if (node.left == null && node.right != null) {
//                return false;
//            } else{ //后面遍历的结点都必须是叶子节点
//                leaf = true;
//                if (node.left != null) {
//                    queue.offer(node.left);
//                }
//            }
//           }
//        return true;
//    }

    //判断是否完全二叉树——第二种写法
    public boolean isCompare(){
        if (root == null)return false;

        Queue<Node<E>> queue = new LinkedList<>();
        queue.offer(root);

        boolean leaf = false;
        while (!queue.isEmpty()) {
            Node<E> node = queue.poll();

            if (leaf && !node.isLeaf()) return false;

            //左边判断
            if (node.left != null) {
                queue.offer(node.left);
            } else if (node.right != null) {
                //node.left == null && node.right != null
                return false;
            }

            //右边判断
            if (node.right != null) {
                queue.offer(node.right);
            } else {
                //node.left == null && node.right == null
                //node.left != null && node.right == null
                leaf = true;
            }
           }
        return true;
    }


    //递归方式
    public int height() {
        return height(root);
    }

    private int height(Node<E> node) {
        if (node ==null) return 0;
        return 1 + Math.max(height(node.left), height(node.right));
    }

    //迭代方式-层序遍历方式
    public int height2() {
        if (root == null) return 0;
        //树的高度
        int height = 0;
        //存储着每一层的元素数量
        int levelSize = 1;
        Queue<Node<E>> queue = new LinkedList<>();
        //入队
        queue.offer(root);
        while (!queue.isEmpty()) {
            //出队
            Node<E> node = queue.poll();
            //这一层的一个元素出队，这一层的元素数量就减一
            levelSize--;
            if (node.left != null) {
                //入队
                queue.offer(node.left);
            }
            if (node.right != null) {
                //入队
                queue.offer(node.right);
            }
            if (levelSize == 0) {//意味着即将要访问下一层
                levelSize = queue.size();
                //这一层访问结束，开始下一层，所以高度要加一
                height++;
            }
        }
        return height;
    }


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        toString(root, sb, "");
        return sb.toString();
    }

    private void toString(Node<E> node, StringBuilder sb, String prefix) {
        if (node == null) return;
        sb.append(prefix).append(node.element).append("\n");

        toString(node.left, sb, prefix + "L---");
        toString(node.right, sb, prefix + "R---");
    }

    /**
     * @param e1
     * @param e2
     * @return 返回值等于0，代表e1和e2相等；
     * 返回值大于0，代表e1大于e2；
     * 返回值小于0，代表e1小于e2
     */
    private int compare(E e1, E e2) {
        if (comparator != null) {
            return comparator.compare(e1, e2);
        }
        return ((Comparable<E>) e1).compareTo(e2);
    }

    //检查值是否为空
    private void elementNotNullCheck(E element) {
        if (element == null) {
            throw new IllegalArgumentException("element must not be null");
        }
    }

    //前驱节点
    private Node<E> predecessor(Node<E> node){
        if (node == null) return null;

        //前驱结点在左子树当中(left.right.right.right...)
        Node<E> p = node.left;
        if (p != null) {
            while (p.right != null) {
                p = p.right;
            }
            return p;
        }
        //从祖父节点中寻找
        while (node.parent != null && node == node.parent.left) {
            node = node.parent;
        }
        //node.parent == null
        //node == node.parent.right

        return node.parent;
    }

    //后继节点
    private Node<E> successor(Node<E> node){
        if (node == null) return null;

        //前驱结点在左子树当中(right.left.left.left...)
        Node<E> p = node.right;
        if (p != null) {
            while (p.left != null) {
                p = p.left;
            }
            return p;
        }
        //从祖父节点中寻找
        while (node.parent != null && node == node.parent.right) {
            node = node.parent;
        }

        return node.parent;
    }


    //访问器
    public static abstract class Visitor<E> {

        boolean stop;
        /**
         *
         * @param element
         * @return 如果返回返回true，就代表停止遍历
         */
        abstract boolean visit(E element);
    }


    @Override
    public Object root() {
        return root;
    }

    @Override
    public Object left(Object node) {
        return ((Node<E>) node).left;
    }

    @Override
    public Object right(Object node) {
        return ((Node<E>) node).right;
    }

    @Override
    public Object string(Object node) {
        Node<E> myNode = (Node<E>) node;
        String parentString = "null";
        if (myNode.parent != null) {
            parentString = myNode.parent.element.toString();
        }
        return myNode.element + "_p(" + parentString + ")";
    }

    private static class Node<E> {
        E element;
        Node<E> left;
        Node<E> right;
        Node<E> parent;

        public Node(E element, Node<E> parent) {
            this.element = element;
            this.parent = parent;
        }

        public boolean isLeaf() {
            return left == null && right == null;
        }

        public boolean hasTwoChildern() {
            return left != null && right != null;
        }

    }
}
